﻿using RXY_Mall.Core;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web;
using System.Web.Http;
using System.Xml;

namespace RXY_Mall.Api.Controllers
{
    [RoutePrefix("WeiXinMP")]
    public class WeiXinMPController : BaseApiController
    {

        /// <summary>
        /// APP微信支付回调
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("AuthCallback")]
        public string AuthCallback(PostModel postModel)
        {
            LogHelper.WriteLog("--------微信回调开始-----------------");
            string result = "success";
            try
            {
                HttpRequest request = HttpContext.Current.Request;
                WxPayJSAPI.ResultNotify resultNotify = new WxPayJSAPI.ResultNotify(request);
                string xml = resultNotify.ProcessNotify3();

                //NameValueCollection form = request.QueryString;
                //StringBuilder query = new StringBuilder();
                ////第一步：取出所有get参数
                ////IDictionary<string, string> parameters = new Dictionary<string, string>();
                //string bodyUserId = "";
                //for (int f = 0; f < form.Count; f++)
                //{
                //    string key = form.Keys[f];
                //    if (key == "user_id")
                //    {
                //        bodyUserId = form[key];
                //    }

                //    query.Append(key).Append(form[key]);
                //}
                LogHelper.WriteLog(string.Format("msg_signature{0} timestamp:{1}, nonce:{2},xml:{3}", postModel.Msg_Signature, postModel.Timestamp, postModel.Nonce, xml));
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.LoadXml(xml);
                var app_id = xmlDoc.FirstChild["AppId"].InnerText;
                var encrypt = xmlDoc.FirstChild["Encrypt"].InnerText;
                if (app_id != "wx5f605c9f79fbe943")
                {
                    return "fail";
                }

                //公众平台上开发者设置的token, appID, EncodingAESKey
                string sToken = "QDG6eK";
                string sAppID = "wx5823bf96d3bd56c7";
                string sEncodingAESKey = "jWmYm7qr5nMoAUwZRjGtBxmz3KA1tkAj3ykkR6q2B2C";

                Tencent.WXBizMsgCrypt wxcpt = new Tencent.WXBizMsgCrypt(sToken, sEncodingAESKey, sAppID);
                string sMsg = "";  //解析之后的明文
                int ret = 0;
                ret = wxcpt.DecryptMsg(postModel.Msg_Signature, postModel.Timestamp, postModel.Nonce, xml, ref sMsg);
                if (ret != 0)
                {
                    System.Console.WriteLine("ERR: Decrypt fail, ret: " + ret);
                    //return;
                }

                if (!string.IsNullOrWhiteSpace(encrypt))
                {

                }


            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
                result = @"<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[异常处理]]></return_msg></xml>";
            }

            return result;
        }

        public class PostModel
        {
            //
            // 摘要:
            //     Signature
            public string Signature { get; set; }
            //
            // 摘要:
            //     Msg_Signature
            public string Msg_Signature { get; set; }
            //
            // 摘要:
            //     Timestamp
            public string Timestamp { get; set; }
            //
            // 摘要:
            //     Nonce
            public string Nonce { get; set; }
            //
            // 摘要:
            //     Token
            public string Token { get; set; }
            //
            // 摘要:
            //     EncodingAESKey
            public string EncodingAESKey { get; set; }
        }

    }
}
